#include <unistd.h>
#include "draw.h"

static FILE * fd=NULL;
static int BBwidth;
static int BBhight;


/** Calcule la valeur entière de sqrt(n).
 *  Compexitée O(log(n))
 */
int isqrt(int n)
{
	int r=2;

	while(n > r+1)
	{
		n-= r+1;
		r+=2;
	}
	return r/2;
}

//-----------------------------------------------------------------------------
void InitDraw(void * arg)
//-----------------------------------------------------------------------------
{
	PS_option_t * ap = (PS_option_t *)arg;

	fd		= ap->fd;
	BBwidth	= ap->w;
	BBhight	= ap->h;

	fprintf(fd, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 0 0 %d %d\n",BBwidth,BBhight);
	fprintf(fd, "/Times findfont\n8 scalefont\nsetfont\n\n");
}


//-----------------------------------------------------------------------------
void DrawLine(vec2_t from, vec2_t to)
//-----------------------------------------------------------------------------
{
	fprintf(fd,"%d %d moveto\n%d %d lineto\nstroke\n",from[0],from[1],to[0],to[1]);
}

void DrawCir(cir_t * cir)
{
	//DrawCir(cir->c, cir->r);
	fprintf(fd,"%d %d %d 0 360 arc\nstroke\n",cir->c[0], cir->c[1], cir->r);//575 716 5 0 360 arc")
}


//-----------------------------------------------------------------------------
void DrawRec(rec_t * rec)
//-----------------------------------------------------------------------------
{
	//DrawRec(rec->c, rec->w, rec->h);
	vec2_t ul, ur, lr, ll;

	ul[0] = rec->c[0]-rec->w/2;	ul[1] = rec->c[1]+rec->h/2;
	ur[0] = rec->c[0]+rec->w/2;	ur[1] = rec->c[1]+rec->h/2;
	lr[0] = rec->c[0]+rec->w/2;	lr[1] = rec->c[1]-rec->h/2;
	ll[0] = rec->c[0]-rec->w/2;	ul[1] = rec->c[1]-rec->h/2;

	DrawLine(ul,ur);
	DrawLine(ur,lr);
	DrawLine(lr,ll);
	DrawLine(ll,ul);
}

//-----------------------------------------------------------------------------
void DrawText(vec2_t c, char * str)
//-----------------------------------------------------------------------------
{
	fprintf(fd,"%d %d moveto\n(%s) show\nstroke\n",c[0],c[1],str);
}


//-----------------------------------------------------------------------------
void DrawLink(cir_t * c1, cir_t * c2)
//-----------------------------------------------------------------------------
{
	vec2_t p1;
	vec2_t p2;
	int hypoth;//énuse
	int	opp;
	int adja;

	opp =c2->c[1] - c1->c[1];
	adja= c2->c[0] - c1->c[0];
	hypoth = isqrt(opp*opp + adja*adja);

	//printf("c1={(%d,%d),%d}\tc2={(%d,%d),%d}\n",c1->c[0],c1->c[1],c1->r,c2->c[0],c2->c[1],c2->r);
	//printf("opp=%d  adja=%d  hypoth=%d\n",opp, adja, hypoth);

	p1[0]=c1->c[0] + (c1->r * adja)/hypoth;
	p1[1]=c1->c[1] +(c1->r * opp)/hypoth;

	p2[0]=c2->c[0] - (c2->r * adja)/hypoth;
	p2[1]=c2->c[1] - (c2->r * opp)/hypoth;

	//printf("p1=(%d,%d) p2=(%d,%d)\n",p1[0],p1[1],p2[0],p2[1]);

	DrawLine(p1,p2);

}


//-----------------------------------------------------------------------------
void flushDraw()
//-----------------------------------------------------------------------------
{
	fprintf(fd,"stroke\n");
}

